<template>
  <!-- <span>组件4：使用滚动图片显示有封面的最新N篇文章（根据栏目的版面布局配置可以获取显示指定栏目下的文章）</span> -->
  <!-- 文章列表为空，仅显示当前栏目名称 -->
  <div class="cms-category-container">
    <a-list
      size="small"
      :bordered="false"
      :split="false"
      v-if="
        currentArticles.articles === undefined ||
        currentArticles.articles === null ||
        currentArticles.articles.length === 0
      "
    >
      <template #header>
        <div class="category-title">
          <div class="category-title-prefix">
            <img />
          </div>
          <div class="category-title-text" style="font-family: 'Microsoft YaHei'">
            {{ category.name }}</div
          >
        </div>
        <div style="height: 1px; width: 100%">
          <a-divider style="border-color: #ccc; height: 1px"
        /></div>
      </template>
    </a-list>

    <!-- 文章列表不为空，显示文章的封面图片滚动列表 -->
    <a-list size="small" :bordered="false" :split="false" v-else>
      <!-- 显示数量为1时只显示一张图片，否则滚动显示 -->
      <Vue3SeamlessScroll
        v-if="displayCount === 1"
        :list="currentArticles.articles"
        class="warp"
        direction="left"
        :hover="true"
      >
        <div class="ul">
          <div class="li" v-for="(item, index) in currentArticles.articles" :key="index">
            <div class="coverImg">
              <img
                :src="getImageFileUrlPrefix + item.cover"
                @click="onClickCoverOrTitleArticles(item.id)"
              />
            </div>
            <!-- <span class="li-title" @click="onClickCoverOrTitleArticles(item.id)">
              {{
                item.title != null && item.title.length > 9
                  ? item.title.slice(0, 9) + '...'
                  : item.title
              }}
            </span> -->
          </div>
        </div>
      </Vue3SeamlessScroll>
      <Vue3SeamlessScroll
        v-else
        :list="currentArticles.articles"
        class="warp"
        direction="left"
        :hover="true"
      >
        <div class="ul-item">
          <div class="li-item" v-for="(item, index) in currentArticles.articles" :key="index">
            <div class="li-img">
              <img
                :src="getImageFileUrlPrefix + item.cover"
                @click="onClickCoverOrTitleArticles(item.id)"
              />
            </div>
            <span class="li-title" @click="onClickCoverOrTitleArticles(item.id)">
              {{
                item.title != null && item.title.length > 9
                  ? item.title.slice(0, 9) + '...'
                  : item.title
              }}
            </span>
          </div>
        </div>
      </Vue3SeamlessScroll>
      <template #header>
        <div class="category-title">
          <div class="category-title-prefix">
            <img />
          </div>
          <div class="category-title-text" style="font-family: 'Microsoft YaHei'">{{
            category.name
          }}</div>

          <!-- 是否显示更多 -->
          <div
            v-if="showMore"
            class="category-title-more cursor-pointer"
            @click="onClickLoadMoreArticles(category)"
            >更多>></div
          >
        </div>

        <div style="height: 1px; width: 100%">
          <a-divider style="border-color: #ccc; height: 1px"
        /></div>
      </template>
    </a-list>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, onMounted, computed } from 'vue';

  import { useGlobSetting } from '/@/hooks/setting';
  import { getImageFileApi } from '/@/api/platform/file';

  import { useGo } from '/@/hooks/web/usePage';
  import { useCmsStore } from '/@/store/modules/cms';
  import { useRouter } from 'vue-router';

  import { queryArticles } from '/@/api/cms/display';
  import { getArticle, viewArticle } from '/@/api/cms/article';

  import { Vue3SeamlessScroll } from 'vue3-seamless-scroll';

  export default defineComponent({
    name: 'CmsCategoryTopNArticleCovers',
    components: { Vue3SeamlessScroll },
    props: {
      category: {},
    },

    setup(props, context) {
      // console.log('使用滚动图片显示最新文章get props', props.category.article);

      const { apiUrl, globalProjectCode } = useGlobSetting();
      const go = useGo();
      //使用store必须在setup中，否则会报错
      const cmsStore = useCmsStore();
      const router = useRouter();
      const projectCode = ref<String>(globalProjectCode);

      const getImageFileUrlPrefix = ref<string>(apiUrl + getImageFileApi);

      const currentArticles = reactive({
        articles: [],
      });

      //从栏目的文章显示配置中获取配置的文章显示数量，默认显示15篇文章
      let displayCount = ref(15);
      //是否打开新的浏览器窗口，默认打开
      let openNewWindow = ref(true);

      onMounted(() => {
        queryTopNArticles();
      });

      //获取当前栏目的文章显示配置中的count显示条数，作为获取top-N有封面文章接口的查询条数
      displayCount = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (articleJson != undefined && articleJson != null) {
              let count = articleJson.count;
              if (count != undefined && count != null) return count;
            }
          }
        }
        return 15;
      });

      //点击文章标题是否打开新的浏览器窗口，默认true打开
      openNewWindow = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (articleJson != undefined && articleJson != null) {
              let newWindow = articleJson.openNewWindow;
              if (newWindow != undefined && newWindow != null && newWindow == false) return false;
            }
          }
        }
        return true;
      });

      //是否显示更多按钮或文字，默认为显示
      let showMore = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let showMore = articleJson.showMore;
              if (!showMore && showMore === false) return false;
            }
          }
        }
        return true;
      });

      //获取top-N有封面的文章
      function queryTopNArticles() {
        // console.log('显示条数', displayCount.value);
        queryArticles({
          cid: props.category.id,
          hasCover: true,
          page: 1,
          pageSize: displayCount.value,
        }).then((res) => {
          // console.log('文章', res);
          currentArticles.articles = res.items;
        });
      }

      /**
       * 点击图片或标题文字跳转对应的文章详情，根据文章内容类型进行不同处理：文章类型为超链接时打开新窗口，为其他类型时跳转至文章查看页面
       * @param articleid
       */
      function onClickCoverOrTitleArticles(articleid) {
        // console.log('点击跳转的文章ID', articleid);
        if (!!articleid && articleid > 0x0) {
          // 根据文章id=获取文章详情，获取文章的内容类型
          getArticle({ id: articleid }).then((res) => {
            console.log('viewArticleDetail res', res);
            if (res.ctype === 3 || res.ctype === '3') {
              //文章内容类型为超链接，打开新窗口
              viewArticle({ id: articleid }).then((res) => {
                window.open(res.content);
              });
            } else {
              if (openNewWindow.value) {
                //打开一个新的浏览器窗口
                const url = router.resolve({
                  path: '/cms/article/' + articleid,
                });
                window.open(url.href);
              } else {
                //使用store存储跳转路由需传递的数据
                cmsStore.setCmsRouteParam({
                  isArticle: true,
                  id: articleid,
                  // data: article,
                });
                go('/cms/article/' + articleid);
              }
            }
          });
        }
      }

      // 点击更多
      const onClickLoadMoreArticles = (category: any) => {
        // console.log('onClickLoadMoreArticles', category);

        let categoryId = category.id;

        //使用store存储跳转路由需传递的数据
        cmsStore.setCmsRouteParam({
          isArticle: false,
          id: categoryId,
          data: category,
        });
        go('/cms/category/' + categoryId);
      };

      return {
        getImageFileUrlPrefix,
        queryTopNArticles,
        currentArticles,
        onClickCoverOrTitleArticles,
        displayCount,
        openNewWindow,
        projectCode,
        showMore,
        onClickLoadMoreArticles,
      };
    },
  });
</script>
<style scoped lang="less">
  @import './cms.less';
  //覆盖antd的默认演示，解决头部高度过大的问题
  .ant-list:deep(.ant-list-header) {
    // line-height: 1;
    padding-bottom: 0px;
  }

  // 滚动列表样式
  // 列表长度不为1时
  .warp {
    min-width: 200px * 4;
    max-width: 300 * 4;
    height: 150px;
    margin: 10px 0px 0px 10px;
    overflow: hidden;
  }
  .ul-item {
    list-style: none;
    padding: 0;
    margin: 0 auto;
    display: flex;
  }
  .li-item {
    width: 160px;
    height: 120px;
    margin-right: 10px;
    line-height: 30px;
    text-align: center;
    font-size: 15px;
  }
  .li-img img {
    cursor: pointer;
    width: 160px;
    height: 100px;
  }
  .li-title {
    cursor: pointer;
  }
  .li-title:hover {
    color: red;
    text-decoration: underline;
  }

  // 列表样式为1时
  .ul {
    width: 100%;
  }
  .li {
    width: 100%;
  }
  .coverImg {
    width: 40%;
  }
  .coverImg img {
    width: 80%;
    margin: 5px 0 0 5px;
    border: 1px solid gray;
    padding: 2px;
    cursor: pointer;
  }
</style>
